import token from "./token";

const BASE_URL = '/health-api';
const TIMEOUT = 5000;

/**
 * 构建完整请求头
 * @param {Object} customHeader 自定义请求头
 */
const buildHeaders = (customHeader = {}) => {
	// 基础请求头
	const headers = {
		'Content-Type': 'application/json;charset=UTF-8',
		...customHeader
	};

	// 自动添加token（如果存在）
	const currentToken = token.getToken();
	if (currentToken) {
		headers['Authorization'] = `Bearer ${currentToken}`;
		headers['Blade-Auth'] = currentToken; // 兼容Blade-Auth
	}

	return headers;
};

/**
 * 主请求函数
 * @param {Object} config 请求配置
 */
const request = (config) => {
	// 解构配置（带默认值）
	const {
		url,
		method = 'GET',
		params = {},
		data = {},
		header = {},
		silent = false // 是否静默模式（不显示错误toast）
	} = config;

	// 处理URL路径
	const processedUrl = url.replace(/^\//, '');
	const fullUrl = `${BASE_URL}/${processedUrl}`;

	// 处理GET查询参数
	const queryString = method.toUpperCase() === 'GET' && Object.keys(params).length > 0 ?
		`?${new URLSearchParams(params).toString()}` :
		'';

	// 完整请求URL
	const requestUrl = fullUrl + queryString;

	return new Promise((resolve, reject) => {
		uni.request({
			url: requestUrl,
			method: method.toUpperCase(),
			data: method.toUpperCase() === 'GET' ? {} : data,
			header: buildHeaders(header),
			timeout: TIMEOUT,
			// 更新响应处理部分
			success: (response) => {
				if (response.statusCode >= 200 && response.statusCode < 300) {
					let resData;
					try {
						// 处理可能的空响应或非JSON响应
						if (typeof response.data === 'string') {
							// 只有非空字符串才尝试解析
							resData = response.data.trim() ? JSON.parse(response.data) : {};
						} else {
							// 如果不是字符串，直接使用原始数据
							resData = response.data || {};
						}

						// 兼容两种成功码：1 和 200
						if (resData?.code !== undefined) {
							if ([1, 200].includes(resData.code)) {
								return resolve(resData);
							}
							handleBusinessError(resData, silent);
							return reject(resData);
						}
						resolve(resData);
					} catch (e) {
						// 如果JSON解析失败，返回原始数据并记录错误
						console.error('JSON解析错误:', e);
						if (e instanceof SyntaxError) {
							// 如果是JSON解析错误，返回原始响应数据
							handleSystemError({
								msg: '数据格式错误',
								data: response.data
							}, silent);
							resolve(response.data || {});
						} else {
							handleSystemError(e, silent);
							reject(e);
						}
					}
				} else {
					handleHttpError(response, silent);
					reject({
						code: response.statusCode,
						msg: getHttpStatusMessage(response.statusCode),
						response
					});
				}
			},
			fail: (err) => {
				handleNetworkError(err, silent);
				reject({
					code: -1,
					msg: '网络连接失败',
					error: err
				});
			}
		});
	});
};

// 错误处理
function handleBusinessError(error, silent) {
	if (error.code === 401) {
		token.removeToken();
		uni.navigateTo({
			url: '/pages/login/index'
		});
	}

	if (!silent) {
		uni.showToast({
			title: error.msg || '操作失败',
			icon: 'none',
			duration: 2000
		});
	}
}

function handleHttpError(response, silent) {
	const errorMap = {
		400: '请求参数错误',
		401: '登录已过期',
		403: '没有操作权限',
		404: '请求资源不存在',
		500: '服务器错误'
	};

	const msg = errorMap[response.statusCode] || `请求失败: ${response.statusCode}`;

	if (!silent) {
		uni.showToast({
			title: msg,
			icon: 'none',
			duration: 2000
		});
	}
}

function handleNetworkError(err, silent) {
	let errMsg = '网络错误';
	if (err.errMsg.includes('timeout')) {
		errMsg = '请求超时';
	}

	if (!silent) {
		uni.showToast({
			title: errMsg,
			icon: 'none',
			duration: 2000
		});
	}
}

function handleSystemError(error, silent) {
	if (!silent) {
		uni.showToast({
			title: error.msg,
			icon: 'none',
			duration: 2000
		});
	}
}

function getHttpStatusMessage(statusCode) {
	const messages = {
		400: '错误的请求',
		401: '未授权',
		403: '禁止访问',
		404: '资源不存在',
		500: '服务器错误'
	};
	return messages[statusCode] || `HTTP错误: ${statusCode}`;
}

request.get = (url, params, config = {}) => {
	return request({
		url,
		method: 'GET',
		params,
		...config
	});
};

request.post = (url, data, config = {}) => {
	return request({
		url,
		method: 'POST',
		data,
		...config
	});
};

export default request;